#include "pintos_thread.h"

struct station {
	// FILL ME IN
	int waitpeople;
	int onpeople; 
	int empty;
	struct lock *train;
	struct condition *come;
	struct condition *finish;
};

void
station_init(struct station *station)
{
	// FILL ME IN
	station->waitpeople=0;
	station->empty=0;
	station->onpeople=0;
	station->train=(struct lock *)malloc(sizeof(struct lock));
	lock_init(station->train);
	station->come=(struct condition *)malloc(sizeof(struct condition));
	cond_init(station->come);
	station->finish=(struct condition *)malloc(sizeof(struct condition));
	cond_init(station->finish);
	
}

void
station_load_train(struct station *station, int count)
{
	// FILL ME IN
	lock_acquire(station->train);
	station->empty=count;
	while (station->empty>0&&station->waitpeople>0)
	{
		cond_broadcast(station->come,station->train);
		cond_wait(station->finish,station->train);
	}
	station->empty=0;
	lock_release(station->train);
	
}

void
station_wait_for_train(struct station *station)
{
	// FILL ME IN
	lock_acquire(station->train);
	station->waitpeople++;
	while (station->onpeople==station->empty)
	{
		cond_wait(station->come,station->train);
	}
	station->waitpeople--;
	station->onpeople++;
	lock_release(station->train);
}

void
station_on_board(struct station *station)
{
	// FILL ME IN
	lock_acquire(station->train);
	station->onpeople--;
	station->empty--;
	if (station->empty==0||(station->onpeople==0&&station->waitpeople==0))
	{
		cond_signal(station->finish,station->train);
	}
	lock_release(station->train);
}
